package mobi.yuanshen.filter;

import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import mobi.yuanshen.utils.JwtUtils;
import mobi.yuanshen.utils.Result;
import org.springframework.util.StringUtils;

import java.io.IOException;

// 过滤器启用，使用拦截器
@Slf4j
//@Component
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

//    @Autowired
    JwtUtils jwtUtils;

//    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {
        // 强转成子类，以便用子类中特有的方法
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        log.info("请求url:{}",requestURI);

        if(requestURI.contains("/login")) {
            filterChain.doFilter(servletRequest,servletResponse); // 放行请求
            return; // 结束方法的运行
        }

        String token = request.getHeader("token");
        log.info("从请求头中获取到了token:{}",token);
        // 判断令牌是否存在，如果不存在，返回错误结果（未登录）
        if (!StringUtils.hasLength(token)) {
            log.info("token不存在");
            Result responseResult = Result.error("NOT_LOGIN");
            String json = JSONObject.toJSONString(responseResult);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return;
        }

        try {
            jwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.info("令牌解析失败!");
            Result responseResult = Result.error("NOT_LOGIN");
            String json = JSONObject.toJSONString(responseResult);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
